package com.wyg.blog.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wyg.blog.utils.JsonResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @description:
 * @author: WYG
 * @time: 2020/6/29 19:48
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Method", "POST,GET");
        httpServletResponse.setStatus(403);
        PrintWriter out = httpServletResponse.getWriter();
        JsonResult jsonResult = new JsonResult();
        jsonResult.setMsg("无权限访问");
        jsonResult.setCode("403");
        jsonResult.setData("请获取权限后再访问");
        out.write(new ObjectMapper().writeValueAsString(jsonResult));
        out.flush();
        out.close();
    }
}
